package com.easy.leetcode.array;

import java.util.Arrays;

/**
 * @ClassName ThreeSumClosest16
 * @Description 16. 最接近的三数之和
 * @Author zheng
 * @Date 2021/10/25 18:28
 * @Version 1.0
 **/
public class ThreeSumClosest16 {
    public int threeSumClosest(int[] nums, int target) {
        //排序
        Arrays.sort(nums);
        int len = nums.length;
        //最相近的值,此处需注意，不能用最大值，可能会越界
        int closest = nums[0]+nums[1]+nums[2];
        for (int i = 0; i < len; i++) {
            int l = i + 1;
            int r = len - 1;
            while (l < r) {
                int tmp = nums[i] + nums[l] + nums[r];
                //相同返回0
                if (tmp == target) {
                    return tmp;
                } else if (tmp < target) {
                    //目标值减去当前值的绝对值，比减去最近值还要小，更新最近值
                    closest = Math.abs(target - tmp) < Math.abs(target - closest) ? tmp : closest;
                    l++;
                } else {
                    closest = Math.abs(target - tmp) < Math.abs(target - closest) ? tmp : closest;
                    r--;
                }
            }
        }
        return closest;
    }
}
